#!/bin/bash
#
# install-sh
#
# note: this file is not named install.sh to avoid unwanted behavior
# due to implicit rules with "make"
#
# installer for joy and related files

usage() { 
    echo "usage:"
    echo ""
    echo "   $0 [ [ -h ] | [ -c configfile ] [ -a anonfile ] [-w watchfile ] [ -k keyfile ] [ -p prefix ] [ -r rootdir ] ]"
    echo ""
    echo "where the options are as follows"
    echo ""
    echo "   The -h flag prints usage information and exits."
    echo ""
    echo "   configfile is the name of a joy configuration file; if no" 
    echo "   such file is provided, then the default configuration options.cfg is used"
    echo ""
    echo "   anonfile is the name of a file containing subnets to be anonymized; if no" 
    echo "   such file is provided, then the default file anon.cfg is used"
    echo ""
    echo "   watchfile is the name of a file containing subnets or addresses to be labeled"
    echo "   as malware; if no such file is provided, then the blacklist ip-filter.blf file"
    echo "   is downloaded and used"
    echo ""
    echo "   keyfile is the name of a file containing an SSH private key to be used"
    echo "   to upload the JSON flow data files to a server via scp; if no such file"
    echo "   is provided, then an SSH file with the default name of upload-key is created" 
    echo ""
    echo "   prefix is the installation prefix (default: /usr/local)"
    echo ""
    echo "   rootdir specifies the package build root directory. Only use when building a package."
    echo ""
    echo "For more information about these files and their formats, please read the"
    echo "joy man page"
    echo ""
} 

# set defaults
#
CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
APP_ROOT=$(dirname "$CWD")
CONFIGFILE=${CWD}/options.cfg
ANONFILE=${APP_ROOT}/internal.net
WATCHFILE=""
KEYFILE=""
NEWKEY=0
TLS_FINGERPRINT_FILE=${APP_ROOT}/resources/tls_fingerprint.json
PREFIX="/usr/local"
BUILDROOT=""
ARCH=`uname -m`
LOGROTATEFILE=/etc/logrotate.d/joy

echo
echo JOY INSTALL-SH
echo --------------------
echo

# check command line arguments, ovveride defaults as appropriate
#
while getopts "hc:a:w:k:p:r:" arg; do
    case $arg in
    h)
        usage
        exit
        ;;
    c)
        echo "-c was triggered with option ${OPTARG}" 
        CONFIGFILE=${OPTARG}
        ;;
    a)
        echo "-a was triggered with option ${OPTARG}" 
        ANONFILE=${OPTARG}
        ;;
    w)
        echo "-w was triggered with option ${OPTARG}" 
        WATCHFILE=${OPTARG}
        ;;
    k)
        echo "-k was triggered with option ${OPTARG}" 
        KEYFILE=${OPTARG}
        ;;
    p)
        echo "-p was triggered with option ${OPTARG}" 
        PREFIX=${OPTARG}
        ;;
    r)
        echo "-r was triggered with option ${OPTARG}" 
        PKGBUILD=true
        BUILDROOT=${OPTARG}
        ;;
    \?)
        echo "error: invalid option -${OPTARG}" 
        usage
        exit 1
        ;;
    :)
        echo "error: option -${OPTARG} requires an argument" 
        usage
        exit 1
        ;;
    esac
done
if [ $(($# + 1)) != "${OPTIND}" ]; then
    echo "error: illegal option"
    usage
    exit 1
fi

# this script requires root privileges; complain and bail otherwise
#
if [ -z "$PKGBUILD" -a "$EUID" -ne 0 ]; then
   echo "error: $0 must be run as root; perhaps run \"sudo $0\"" 
   exit 1
fi

# check for the presence of required files
#
if [ ! -x ${APP_ROOT}/bin/joy ]; then
    echo "error: could not find executable file joy (please run \"make\")"
    exit 1
fi

if [ ! -f ${APP_ROOT}/doc/joy.1 ]; then
    echo "error: could not find manual page joy.1"
    exit 1
fi

if [ ! -f ${CWD}/joy.rc ]; then
    echo "error: could not find script joy.rc"
    exit 1
fi

if [ ! -f $CONFIGFILE ]; then
    echo "error: could not find configuration file $CONFIGFILE"
    exit 1
fi

if [ ! -f ${ANONFILE} ]; then
    echo "error: could not find private address configuration file ${ANONFILE}"
    exit 1
fi

if [ "${KEYFILE}" == "" ]; then
    # set default name for upload key file 
    #
    KEYFILE=upload-key  
fi
if [ -f ${KEYFILE} ]; then 
    echo "file ${KEYFILE} exists; not overwriting it"
    NEWKEY=0
else
    if [ -z "$PKGBUILD" ]; then
        echo "generating SSH public/private keypair ... "
        ssh-keygen -f ${KEYFILE} -P "" -t rsa -b 2048
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not generate SSH key ${KEYFILE}"
            exit
        fi
        if [ ! -f ${KEYFILE} ]; then
            echo "error: could not find keyfile ${KEYFILE}"
            exit 1
        fi
        NEWKEY=1
    else
        echo "Did not build SSH public/private keypair due to package build"
    fi
fi

create_directory () {
    if [ ! -d $1 ]; then
        mkdir -p $1
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not make directory $1"
            exit 1
        fi
    else
        echo "directory $1 already exists"
    fi
}

sysname=`uname -s`

if [ "$sysname" == "Darwin" ]; then
    ##
    # Darwin operating system detected
    ##
    OSXVER=`sw_vers -productVersion | awk -F. '{print $1"."$2}'`
    echo "found $sysname (Mac OS X $OSXVER), installing joy ..."

    if [ -z "$PKGBUILD" ]; then
        echo "stopping flow capture daemon (just in case one is already running)"
        launchctl unload /Library/LaunchDaemons/joy.plist
        launchctl unload /Library/LaunchAgents/com.cisco.joy.plist

        # Create or update joy group
        #
        OLDGID=$(dscl . -read /Groups/joy PrimaryGroupID 2>/dev/null | awk '{print $2}')
        if [ -z "$OLDGID" ]; then
            # joy group does not exist; find next available GID
            MAXGID=$(dscl . -list /Groups PrimaryGroupID | awk '{print $2}' | sort -ug | tail -1)
            NEWGID=$((MAXGID+1))
        else
            # joy group already exists; re-use existing GID
            NEWGID=$OLDGID
        fi
        echo "creating/updating joy group"
        dscl . -create /Groups/joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not create joy group"
            exit 1
        fi
        dscl . -create /Groups/joy PrimaryGroupID $NEWGID
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not create joy group with GID $NEWGID"
            exit 1
        fi
        dscl . -create /Groups/joy Password \*
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not update joy group Password"
            exit 1
        fi
        dscl . -create /Groups/joy RealName "joy group"
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not update joy group RealName"
            exit 1
        fi
        
        # Create or update joy user
        #
        OLDUID=$(dscl . -read /Users/joy UniqueID 2>/dev/null | awk '{print $2}')
        if [ -z "$OLDUID" ]; then
            # joy user does not exist; find next available UID
            MAXUID=$(dscl . -list /Users UniqueID | awk '{print $2}' | sort -ug | tail -1)
            NEWUID=$((MAXUID+1))
        else
            # joy group already exists; re-use existing UID
            NEWUID=$OLDUID
        fi
        echo "creating/updating joy user"
        dscl . -create /Users/joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not create joy user"
            exit 1
        fi
        dscl . -create /Users/joy Password \*
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user Password"
            exit 1
        fi
        dscl . -create /Users/joy RealUser "Joy User"
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user RealUser"
            exit 1
        fi
        dscl . -create /Users/joy UserShell /usr/bin/false
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user UserShell"
            exit 1
        fi
        dscl . -create /Users/joy UniqueID $NEWUID
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user UniqueID $NEWUID"
            exit 1
        fi
        dscl . -create /Users/joy PrimaryGroupID $NEWGID
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user PrimaryGroupID $NEWGID"
            exit 1
        fi
        dscl . -create /Users/joy NFSHomeDirectory /var/empty
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not set joy user NFSHomeDirectory"
            exit 1
        fi
        dscl . -delete /Users/joy AuthenticationAuthority
        dscl . -delete /Users/joy PasswordPolicyOptions
    fi # PKGBUILD

    # Create ${PREFIX}/bin directory if it does not currently exist
    create_directory ${PREFIX}/bin

    # Create ${PREFIX}/var directory if it does not currently exist
    create_directory ${PREFIX}/var

    # Create ${PREFIX}/var/joy directory if it does not currently exist
    create_directory ${PREFIX}/var/joy
    if [ -z "$PKGBUILD" ]; then
        chown -R joy:joy ${PREFIX}/var/joy
        chmod 775 ${PREFIX}/var/joy
    fi

    # Create ${PREFIX}/var/log directory if it does not currently exist
    create_directory ${PREFIX}/var/log
    if [ -z "$PKGBUILD" ]; then
        chown -R joy:joy ${PREFIX}/var/log
        chmod 775 ${PREFIX}/var/log
    fi

    # Create ${PREFIX}/etc directory if it does not currently exist
    create_directory ${PREFIX}/etc

    # Create ${PREFIX}/etc/joy directory if it does not currently exist
    create_directory ${PREFIX}/etc/joy

    # Create ${PREFIX}/share directory if it does not currently exist
    create_directory ${PREFIX}/share

    # Create ${PREFIX}/share/man directory if it does not currently exist
    create_directory ${PREFIX}/share/man

    # Create ${PREFIX}/share/man/man1 directory if it does not currently exist
    create_directory ${PREFIX}/share/man/man1

    # Install the binary executable
    cp ${APP_ROOT}/bin/joy ${PREFIX}/bin
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy joy to ${PREFIX}/bin"
        exit 1
    fi

    # Install the joy uninstall script
    if [ -z "$PKGBUILD" ]; then
        cp ${CWD}/uninstall-sh ${PREFIX}/bin/uninstall-joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy uninstall-joy to ${PREFIX}/bin"
            exit 1
        fi
    else
        cp ${CWD}/uninstall-joy-pkg ${PREFIX}/bin
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy uninstall-joy-pkg to ${PREFIX}/bin"
            exit 1
        fi
    fi

    # Install sleuth script
    cp ${APP_ROOT}/sleuth ${PREFIX}/bin/
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy sleuth to ${PREFIX}/bin/"
        exit 1
    fi

    # Install the sleuth python module
    if [ -z "$PKGBUILD" ]; then
        echo "Running pip install ${APP_ROOT}/sleuth_pkg/"
        pip install ${APP_ROOT}/sleuth_pkg/
    else
        cd ${APP_ROOT}/sleuth_pkg
        SLEUTHVER=`grep version setup.py | awk -F\' '{print $2}'`
        echo "Running python setup.py bdist --format=gztar"
        python setup.py bdist --format=gztar
        if [ $retval -ne "0" ]; then
            echo "error: could not run python setup.py for sleuth_pkg"
            exit 1
        fi
        SLEUTHFILE="${APP_ROOT}/sleuth_pkg/dist/sleuth-${SLEUTHVER}.macosx-${OSXVER}-${ARCH}.tar.gz"
        if [ -f $SLEUTHFILE ]; then
            tar -xf $SLEUTHFILE -C $BUILDROOT
        else
            echo "Cannot find sleuth tarball $SLEUTHFILE"
            exit 1
        fi
    fi

    # Install the configuration file
    if [ -f ${PREFIX}/etc/joy/options.cfg ]; then
        echo "warning: file ${PREFIX}/etc/joy/options.cfg exists; renaming that file to options.cfg.bak"
        mv ${PREFIX}/etc/joy/options.cfg ${PREFIX}/etc/joy/options.cfg.bak 
    else
        cp ${CONFIGFILE} ${PREFIX}/etc/joy/options.cfg
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${CONFIGFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the tls fingerprint file
    if [ -f ${PREFIX}/etc/joy/${TLS_FINGERPRINT_FILE} ]; then
        echo "file ${PREFIX}/etc/joy/${TLS_FINGERPRINT_FILE} exists; not installing tls fingerprint file"
    else
        cp ${TLS_FINGERPRINT_FILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${TLS_FINGERPRINT_FILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the anonymization file
    if [ -f ${PREFIX}/etc/joy/${ANONFILE} ]; then
        echo "file ${PREFIX}/etc/joy/${ANONFILE} exists; not installing anonymization subnet file"
    else
        cp ${ANONFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${ANONFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the ssh key file
    if [ -z "$PKGBUILD" ]; then
        mv ${KEYFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not move ${KEYFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
        chmod 600 ${PREFIX}/etc/joy/${KEYFILE}
    fi


    if [ "${WATCHFILE}" != "" ]; then
        # Install the watch file
        if [ -f ${PREFIX}/etc/joy/${WATCHFILE} ]; then
            echo "file ${PREFIX}/etc/joy/${WATCHFILE} exists; overwriting with recent file"
        fi
        cp ${WATCHFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${WATCHFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the Launchd script for daemon management
    if [ -z "$PKGBUILD" ]; then
        cp ${CWD}/joy.plist /Library/LaunchAgents/com.cisco.joy.plist
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy joy.plist to /Library/LaunchAgents"
            exit 1
        fi
    else
        # Copy joy.plist for pkg post-installation
        create_directory ${PREFIX}/etc/joy/
        cp ${CWD}/joy.plist ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy joy.plist to ${PREFIX}/etc/joy/"
            exit 1
        fi
    fi

    # Install the manpage documentation
    cp ${APP_ROOT}/doc/joy.1 ${PREFIX}/share/man/man1/
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy joy.1 to ${PREFIX}/share/man/man1 (man page will be unavailable)"
        exit 1
    fi

    if [ -z "$PKGBUILD" ]; then
        ls -l ${PREFIX}/bin/joy
        ls -l ${PREFIX}/bin/uninstall-joy
        ls -l ${PREFIX}/etc/joy/*
        ls -l ${PREFIX}/share/man/man1/joy.1
        ls -l /Library/LaunchAgents/com.cisco.joy.plist
        echo "starting flow capture daemon"
        launchctl load /Library/LaunchAgents/com.cisco.joy.plist
    fi

    echo "...done"
    echo

elif [ "$sysname" == "Linux" ]; then 
    ##
    # Linux operating system detected
    ##
    echo "found $sysname (Linux), installing joy ..."

    # Default to sysv for daemon management system
    daemon_system='sysv'
    if [ -f /sbin/init ]; then
        # Check if the file is a symbolic link
        if [ -h /sbin/init ]; then
            # Check whether linked to systemd
            file /sbin/init | grep -q 'systemd'
            retval=$?
            if [ $retval == "0" ]; then
                daemon_system='systemd'
            fi
        fi
    fi

    # Create joy user and group
    if [ -z "$PKGBUILD" ]; then
        getent group joy &>/dev/null || /usr/sbin/groupadd -r joy
        getent passwd joy &>/dev/null || /usr/sbin/useradd -g joy -s /sbin/nologin -M -r -d / joy
    fi

    # Create ${PREFIX}/bin directory if it does not currently exist
    create_directory ${PREFIX}/bin

    # Create ${PREFIX}/var directory if it does not currently exist
    create_directory ${PREFIX}/var

    # Create ${PREFIX}/var/joy directory if it does not currently exist
    create_directory ${PREFIX}/var/joy
    if [ -z "$PKGBUILD" ]; then
        chown -R joy.joy ${PREFIX}/var/joy
        chmod 775 ${PREFIX}/var/joy
    fi

    # Create ${PREFIX}/var/log directory if it does not currently exist
    create_directory ${PREFIX}/var/log
    if [ -z "$PKGBUILD" ]; then
        chown -R joy.joy ${PREFIX}/var/log
        chmod 775 ${PREFIX}/var/joy
    fi

    # Create ${PREFIX}/etc directory if it does not currently exist
    create_directory ${PREFIX}/etc

    # Create ${PREFIX}/etc/joy directory if it does not currently exist
    create_directory ${PREFIX}/etc/joy

    # Create ${PREFIX}/share directory if it does not currently exist
    create_directory ${PREFIX}/share

    # Create ${PREFIX}/share/man directory if it does not currently exist
    create_directory ${PREFIX}/share/man

    # Create ${PREFIX}/share/man/man1 directory if it does not currently exist
    create_directory ${PREFIX}/share/man/man1

    # Create ${PREFIX}/share/joy directory if it does not currently exist
    create_directory ${PREFIX}/share/joy

    # Create ${PREFIX}/share/joy/data directory if it does not currently exist
    #create_directory ${PREFIX}/share/joy/data

    # Stop service, if a previous version is already running
    if [ -z "$PKGBUILD" ]; then
        echo "stopping service (this might take some time)" 
        if [ "$daemon_system" == "sysv" ]; then
            service joy stop 
        elif [ "$daemon_system" == "systemd" ]; then
            systemctl stop joy.service
        fi
    fi

    # Install the binary executable
    cp ${APP_ROOT}/bin/joy ${PREFIX}/bin/
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy joy to ${PREFIX}/bin/"
        exit 1
    fi

    # Install the joy uninstall script
    if [ -z "$PKGBUILD" ]; then
        cp ${CWD}/uninstall-sh ${PREFIX}/bin/uninstall-joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy uninstall-joy to ${PREFIX}/bin"
            exit 1
        fi
    fi

    # Install sleuth script
    cp ${APP_ROOT}/sleuth ${PREFIX}/bin/
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy sleuth to ${PREFIX}/bin/"
        exit 1
    fi

    # Install the sleuth python module
    if [ -z "$PKGBUILD" ]; then
        pip install ${APP_ROOT}/sleuth_pkg/
    else
	cd ${APP_ROOT}/sleuth_pkg
	SLEUTHVER=`grep version setup.py | awk -F\' '{print $2}'`
	echo "Running python setup.py bdist --format=gztar"
	python setup.py bdist --format=gztar
        if [ $retval -ne "0" ]; then
            echo "error: could not run python setup.py for sleuth_pkg"
            exit 1
        fi
        SLEUTHFILE="${APP_ROOT}/sleuth_pkg/dist/sleuth-${SLEUTHVER}.linux-${ARCH}.tar.gz"
	if [ -f $SLEUTHFILE ]; then
            tar -xf $SLEUTHFILE -C $BUILDROOT
	else
            exit 1
        fi
        SLEUTHFILE="${APP_ROOT}/sleuth_pkg/dist/sleuth-${SLEUTHVER}.linux-${ARCH}.tar.gz"
	if [ -f $SLEUTHFILE ]; then
            tar -xf $SLEUTHFILE -C $BUILDROOT
	else
            echo "Cannot find sleuth tarball $SLEUTHFILE"
            exit 1
	fi
    fi

    # Install the configuration file
    if [ -f ${PREFIX}/etc/joy/options.cfg ]; then
        echo "warning: file ${PREFIX}/etc/joy/options.cfg exists; renaming that file to options.cfg.bak"
        mv ${PREFIX}/etc/joy/options.cfg ${PREFIX}/etc/joy/options.cfg.bak 
    else
        cp ${CONFIGFILE} ${PREFIX}/etc/joy/options.cfg
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy options.cfg to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the tls fingerprint file
    if [ -f ${PREFIX}/etc/joy/${TLS_FINGERPRINT_FILE} ]; then
        echo "file ${PREFIX}/etc/joy/${TLS_FINGERPRINT_FILE} exists; not installing tls fingerprint file"
    else
        cp ${TLS_FINGERPRINT_FILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${TLS_FINGERPRINT_FILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the anonymization file
    if [ -f ${PREFIX}/etc/joy/${ANONFILE} ]; then
        echo "file ${PREFIX}/etc/joy/${ANONFILE} exists; not installing subnet file"
    else
        cp ${ANONFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${ANONFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the ssh key file
    if [ -z "$PKGBUILD" ]; then
        mv ${KEYFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not move ${KEYFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
        chmod 600 ${PREFIX}/etc/joy/${KEYFILE}
    fi

    if [ "${WATCHFILE}" != "" ]; then
        # Install the watch file
        if [ -f ${PREFIX}/etc/joy/${WATCHFILE} ]; then
            echo "file ${PREFIX}/etc/joy/${WATCHFILE} exists; overwriting with recent file"
        fi
        cp ${WATCHFILE} ${PREFIX}/etc/joy/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy ${WATCHFILE} to ${PREFIX}/etc/joy"
            exit 1
        fi
    fi

    # Install the manpage documentation
    cp ${APP_ROOT}/doc/joy.1 ${PREFIX}/share/man/man1/
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy joy.1 to ${PREFIX}/share/man/man1/"
        exit 1
    fi
    if [ -z "$PKGBUILD" ]; then
        mandb >/dev/null
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not run mandb (man page will be unavailable)"
            # exit 1
        fi
    fi

    #cp ${APP_ROOT}/data/* ${PREFIX}/share/joy/data
    #retval=$?
    #if [ $retval -ne "0" ]; then
        #echo "error: could not copy data files into directory ${PREFIX}/share/joy/data"
        #exit 1
    #fi

    ##
    # Copy the daemon service files and start it
    ##
    if [ "$daemon_system" == "sysv" ]; then
        create_directory $BUILDROOT/etc/init.d
        cp ${CWD}/joy.rc $BUILDROOT/etc/init.d/joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy to $BUILDROOT/etc/init.d"
            exit 1
        fi
        chmod +x /etc/init.d/joy
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not chmod +x $BUILDROOT/etc/init.d/joy"
            exit 1
        fi
        if [ -z "$PKGBUILD" ]; then
            # Configure to run automatically at boot time
            update-rc.d joy defaults
            retval=$?
            if [ $retval -ne "0" ]; then
                echo "error: update-rc.d failed (return value: $retval)"
                exit 1
            fi

            # Start service 
            service joy start
        fi
    elif [ "$daemon_system" == "systemd" ]; then
        create_directory ${BUILDROOT}/usr/lib/systemd/system
        cp ${CWD}/joy.service ${BUILDROOT}/usr/lib/systemd/system/
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy joy.service to ${BUILDROOT}/usr/lib/systemd/system/"
            exit 1
        fi
        chmod 644 ${BUILDROOT}/usr/lib/systemd/system/joy.service
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not chmod 644 ${BUILDROOT}/usr/lib/systemd/system/joy.service"
            exit 1
        fi
        create_directory ${BUILDROOT}/etc/systemd/system/joy.service.d
        cp ${CWD}/joy-accounting.conf ${BUILDROOT}/etc/systemd/system/joy.service.d/20-accounting.conf
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not copy joy-accounting.conf to ${BUILDROOT}/etc/systemd/system/joy.service.d/20-accounting.conf"
            exit 1
        fi
        chmod 644 ${BUILDROOT}/etc/systemd/system/joy.service.d/20-accounting.conf
        retval=$?
        if [ $retval -ne "0" ]; then
            echo "error: could not chmod 644 ${BUILDROOT}/etc/systemd/system/joy.service.d/20-accounting.conf"
            exit 1
        fi

        if [ -z "$PKGBUILD" ]; then
            # Reload systemd to enable accounting
            systemctl daemon-reload

            # Configure to run at boot time
            systemctl enable joy.service

            # Start service
            systemctl start joy.service
        fi
    fi

    # Install the logrotate configuration file
    create_directory $BUILDROOT/etc/logrotate.d
    cp ${CWD}/joy.logrotate ${BUILDROOT}${LOGROTATEFILE}
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not copy joy.logrotate to ${BUILDROOT}${LOGROTATEFILE}"
        exit 1
    fi
    chmod 644 ${BUILDROOT}${LOGROTATEFILE}
    retval=$?
    if [ $retval -ne "0" ]; then
        echo "error: could not chmod 644 ${BUILDROOT}${LOGROTATEFILE}"
        exit 1
    fi

    # List all the installed files
    if [ -z "$PKGBUILD" ]; then
        ls -l ${PREFIX}/bin/joy
        ls -l ${PREFIX}/bin/sleuth
        ls -l ${PREFIX}/etc/joy/*
        ls -l ${PREFIX}/share/man/man1/joy.1

        if [ "$daemon_system" == "sysv" ]; then
            ls -l /etc/init.d/joy
            service joy status
        elif [ "$daemon_system" == "systemd" ]; then
            ls -l /usr/lib/systemd/system/joy.service
            ls -l /etc/systemd/system/joy.service.d/20-accounting.conf
            systemctl status joy.service
        fi
        [ -f "$LOGROTATEFILE" ] && ls -l ${LOGROTATEFILE}
    fi

    echo "done" 
    echo
else

    echo "error: unknown system ($sysname)"
    exit 1

fi

if [ "$NEWKEY" -eq "1" ]; then

    echo "A new SSH key was generated, and its private key was installed in"
    echo "the ${PREFIX}/etc/joy directory.  To use this key to authenticate scp"
    echo "connections to a server that copy the JSON files, you will need to"
    echo "provide the public key ${KEYFILE}.pub to the server administrator,"
    echo "as it needs to be installed in the ./ssh/known_hosts file."

fi
